import 'package:flutter/material.dart';
import 'package:flutter_web_socket/util/toast_util.dart';
import 'package:flutter_web_socket/web_socket_page.dart';

/// 首页
class HomePage extends StatefulWidget {
  const HomePage({super.key, required this.title});

  /// 页面标题
  final String title;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  /// TextField操作控制器
  final TextEditingController _editingController =
      TextEditingController(text: "ws://127.0.0.1:9001/ws");

  /// 跳转到WebSocket页面
  void _goWebSocketPage(BuildContext context, String url) {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return WebSocketPage(
        url: url,
      );
    }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.primary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding:
                  const EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0),
              child: TextField(
                controller: _editingController,
                decoration: InputDecoration(
                  //左侧图标
                  icon: const Icon(Icons.person),
                  //提示文字
                  hintText: "请输入连接地址：",
                  //边框
                  border: const OutlineInputBorder(),
                  //右侧按钮
                  suffixIcon: IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () {
                      //清除输入框内容
                      _editingController.clear();
                    },
                  ),
                ),
              ),
            ),
            ElevatedButton(
              child: const Text("WebSocket测试"),
              onPressed: () {
                //连接地址
                var url = _editingController.text;
                if (url.isEmpty) {
                  ToastUtil.toast("请输入连接地址");
                  return;
                }
                // 跳转到WebSocket页面
                _goWebSocketPage(context, url);
              },
            ),
          ],
        ),
      ),
    );
  }
}
